package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTyperList() {
        String key = SHOP_TYPE_KEY;
        // 从 Redis 中获取列表大小
        Long size = stringRedisTemplate.opsForList().size(key);
        List<ShopType> typeList = new ArrayList<>();
        // 如果 Redis 中有数据
        if (size != null && size > 0) {
            List<String> redisData = stringRedisTemplate.opsForList().range(key, 0, -1);
            for (String s : redisData) {
                typeList.add(JSONUtil.toBean(s, ShopType.class));
            }
            return Result.ok(typeList);
        }
        try {
            // 从数据库中查询数据
            typeList = query().orderByAsc("sort").list();
            if (typeList.isEmpty()) {
                // 处理缓存穿透，将空列表存入 Redis
                stringRedisTemplate.opsForList().leftPushAll(key, new ArrayList<>());
                stringRedisTemplate.expire(key, SHOP_TYPE_TTL, TimeUnit.MINUTES);
                return Result.fail("未找到店铺类型数据");
            }
            // 将数据存入 Redis
            List<String> tempShopType = new ArrayList<>(typeList.size());
            for (ShopType shopType : typeList) {
                tempShopType.add(JSONUtil.toJsonStr(shopType));
            }
            stringRedisTemplate.opsForList().leftPushAll(key, tempShopType);
            stringRedisTemplate.expire(key, SHOP_TYPE_TTL, TimeUnit.MINUTES);
            return Result.ok(typeList);
        } catch (Exception e) {
            // 处理数据库查询异常
            e.printStackTrace();
            return Result.fail("查询店铺类型列表失败");
        }
    }
}
